package paypal

import (
	"context"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/plutov/paypal/v4"
)

type SPayPal struct {
	clientId  string
	secret    string
	username  string
	password  string
	host      string
	signatrue string
	intent    string
	webHookId string // web钩子秘钥
}

type (
	// OtherParam 支付其他参数
	OtherParam struct {
		Currency  string
		Content   string
		ReturnUrl string
		CancelUrl string
		LinkRel   string
	}
)

const (
	defaultLinkRel = `approve` // 默认支付链接类型
)

// Config 获取配置
func (p *SPayPal) Config(config map[string]*gvar.Var) error {
	if config == nil {
		return errors.New(`PayPal payment configuration is empty`)
	}
	// 客户端ID
	clientId, ok := config[`paypal_client_id`]
	if !ok {
		return errors.New(`PayPal payment client ID is empty`)
	}
	p.clientId = clientId.String()

	// 密钥
	secret, ok := config[`paypal_secret`]
	if !ok {
		return errors.New(`PayPal payment secret is empty`)
	}
	p.secret = secret.String()

	// 账户名
	username, ok := config[`paypal_username`]
	if !ok {
		return errors.New(`PayPal payment username is empty`)
	}
	p.username = username.String()

	// 密码
	password, ok := config[`paypal_password`]
	if !ok {
		return errors.New(`PayPal payment password is empty`)
	}
	p.password = password.String()

	// 签名
	signatrue, ok := config[`paypal_signatrue`]
	if !ok {
		return errors.New(`PayPal payment signatrue is empty`)
	}
	p.signatrue = signatrue.String()

	// 支付域名
	host, ok := config[`paypal_host`]
	if !ok {
		return errors.New(`PayPal payment host is empty`)
	}
	p.host = host.String()

	// 结算方式
	intent, ok := config[`paypal_intent`]
	if !ok {
		return errors.New(`PayPal payment intent is empty`)
	}
	p.intent = intent.String()

	// 事件秘钥ID
	p.webHookId = config[`paypal_webhook_id`].String()
	return nil
}

// Client 实例PayPal支付客户端
func (p *SPayPal) Client(ctx context.Context) (*paypal.Client, error) {
	client, err := paypal.NewClient(p.clientId, p.secret, p.host)
	if err != nil {
		return nil, fmt.Errorf(`实例客户端失败%w`, err)
	}

	// 获取授权token
	_, err = client.GetAccessToken(ctx)
	if err != nil {
		return nil, fmt.Errorf(`获取AccessToken失败%w`, err)
	}

	return client, nil
}
